
import { ItemModel } from 'js/model/itemModel'
import { BagModel } from 'js/model/bagModel'
import itemHandle from './itemHandle'
import { gameConfigHandle } from 'js/config/gameConfig'
import Random from 'js/core/random'
import { BagType } from 'js/typeDefine/typeDefine'
import { PlayerModel } from 'js/model/playerModel'

const MAXSTACK = 9999999

class BagHandle {

    constructor() {

    }
    initPackag(bag: BagModel) {
        let size = this.getBagSize(bag)
        bag.emptySize = size

        let items = new Array(size)
        for (let i = 0; i < size; i++) {
            let item = bag.items[i]
            if (item) {
                if (gameConfigHandle.configByID[item.tID]) {
                    item = new ItemModel(item)
                    bag.emptySize -= 1
                    item.pos = i
                    items[i] = item
                } else {
                    items[i] = null
                }
            } else {
                items[i] = null
            }
        }
        bag.items = items
    }

    clear(bag: BagModel) {
        let size = this.getBagSize(bag)
        for (let i = 0; i < size; i++) {
            bag.items[i] = null
        }
        bag.emptySize = this.getBagSize(bag)
    }
    getBagSize(bag: BagModel) {
        let addSize = bag.addSize || 0
        return gameConfigHandle.gameConfig.base.bagSize + addSize
    }

    //获取背包中物品数量
    getBagItemSize(bag: BagModel) {
        return this.getBagSize(bag) - bag.emptySize
    }
    //通过物品id 从背包中找到该物品并返回它
    getItemByID(bag: BagModel, itemID: number, hp?: number): ItemModel[] {
        hp = hp || 0
        let items: ItemModel[] = []
        let size = this.getBagSize(bag)
        for (let i = 0; i < size; i++) {
            let item = bag.items[i]
            if (item) {
                if (item.tID === itemID) {
                    if (hp != 0) {
                        if (item.hp && item.hp == hp) {
                            items.push(item)
                        }
                    } else {
                        items.push(item)
                    }
                }
            }
        }
        return items
    }

    //通过物品的id 持久度 从背包找到它并返回它
    getItemByIDByHp(bag: BagModel, itemID: number, hp: number): ItemModel[] {
        let items: ItemModel[] = []
        let size = this.getBagSize(bag)
        for (let i = 0; i < size; i++) {
            let item = bag.items[i]
            if (item) {
                if (item.tID === itemID && item.hp && item.hp == hp) {
                    items.push(item)
                }
            }
        }
        return items
    }


    // 添加物品组  成功返回0   背包空间不足添加失败返回-1
    AddItems(bag: BagModel, items: ItemModel[]) {
        let size = this.getBagSize(bag)
        if (bag.emptySize < size) {
            return -1 // 背包空间不足
        }
        for (let i = 0; i < size; i++) {
            let item = items[i]
            this.AddItemComponent(bag, item)
        }
        return 0
    }

    //itemHandle.create({ tID, stack, pos, hp, isNew }: any, rand): ItemModel 
    // 添加物品
    AddItem(bag: BagModel, itemId: number, num: number, rand: Random, hp?: number) {
        if (!gameConfigHandle.configByID[itemId]) {
            console.log(`${itemId}该物品不存在`)
            return
        }
        hp = hp || 0
        let item = itemHandle.create({ tID: itemId, stack: num, isNew: true, hp: hp }, rand)
        return this.AddItemComponent(bag, item)
    }

    // 添加物品
    AddItemComponent(bag: BagModel, item: ItemModel): boolean {
        // 判断背包是否有空
        if (bag.emptySize === 0) {
            return false
        }
        // 判断物品是否可以叠加
        let itemConfig = gameConfigHandle.configByID[item.tID]
        let single = itemConfig.single
        let itemInfoId: ItemModel[]
        if (single) {
            itemInfoId = []
        } else {
            // 查找物品是否已经存在
            itemInfoId = this.getItemByID(bag, item.tID, item.hp)
        }

        if (itemInfoId.length === 0) {
            // 不存在，添加到空格子
            this._addItemToPosition(bag, item)
        } else {
            let maxStack = itemConfig.MaxStack || MAXSTACK
            let num = item.stack || 1 // 叠加数
            for (let i = 0; i < itemInfoId.length; i++) {
                let p = itemInfoId[i]
                let stack = p.stack

                if ((stack + num) <= maxStack) {
                    p.stack = stack + num
                    num = 0
                    return true
                } else {
                    num = stack + num - maxStack
                    p.stack = maxStack
                }
            }
            if (num > 0) {
                // 剩余的数量添加到空格子
                item.stack = num
                this._addItemToPosition(bag, item)
            }
        }
        return true
    }

    // 添加物品到空格子
    _addItemToPosition(bag: BagModel, item: ItemModel) {
        let pos = this._getEmpty(bag) // 获取空格子的下标
        if (pos === -1) {
            return -1
        }
        item.pos = pos
        bag.emptySize -= 1 // 空格子数量减一
        bag.items[pos] = item
        // let itemInfoId = this.itemsByID[item.tID] // 查找物品是否已经存在 if (itemInfoId) {   itemInfoId.push(item)
        // } else {   this.itemsByID[item.tID] = [item] }
    }

    // 获取一个空格子的下标
    _getEmpty(bag: BagModel) {
        if (bag.emptySize === 0) {
            return -1
        }
        let size = this.getBagSize(bag)
        for (let i = 0; i < size; i++) {
            if (!bag.items[i]) {
                return i
            }
        }
    }

    IsHasEmpty(bag: BagModel, number?: number): boolean {
        number = number || 1
        if (bag.emptySize >= number) {
            return true
        } else {
            return false
        }
    }

    //移除包裹中的物品
    removeItemByItemId(bag: BagModel, ItemID, num: number) {
        num = Math.floor(num)
        let itemInfoById = this.getItemByID(bag, ItemID)
        for (let i = itemInfoById.length - 1; i >= 0; i--) {
            let p = itemInfoById[i]
            let stack = p.stack
            if (stack > num) {
                p.stack -= num
                p.stack = Math.floor(p.stack)
                return 0
            } else if (stack === num) {
                this.removeItemByPosition(bag, p.pos)
                return 0
            } else {
                num -= p.stack
                this.removeItemByPosition(bag, p.pos)
            }
        }
        return 0
    }

    // 根据下标删除背包中的物品
    removeItemByPosition(bag: BagModel, pos: number) {
        let item = bag.items[pos]
        if (!item) {
            return 1
        }
        bag.emptySize += 1 // 空格子加一
        bag.items[pos] = null
        return 0
    }

    //删除下标位置的物品指定数量
    removeSomeItemByPosition(bag: BagModel, pos: number, num: number) {
        if (bag.items[pos].stack === num) {
            this.removeItemByPosition(bag, pos)
        } else if (bag.items[pos].stack < num) {
            return 1
        } else {
            bag.items[pos].stack -= num
        }
        return 0
    }

    //取出下标位置的物品指定数量
    getSomeItemByPosition(bag: BagModel, pos: number, num: number, rand: Random): ItemModel {
        if (bag.items[pos].stack === num) {
            let item = bag.items[pos]
            this.removeItemByPosition(bag, pos)
            return item
        } else if (bag.items[pos].stack < num) {

            return null
        } else {
            bag.items[pos].stack -= num
            let item = itemHandle.create(bag.items[pos], rand)
            item.stack = num
            return item
        }
    }

    // 获取某一物品的总数量
    getTotalNumByItemId(bag: BagModel, itemID: number, itemLvl?: any) {
        let total = 0
        let size = this.getBagSize(bag)
        for (let i = 0; i < size; i++) {
            let item = bag.items[i]
            if (item) {
                if (item.tID === itemID) {
                    if (itemLvl && item.hp === itemLvl) {
                        total += item.stack || 0
                    } else {
                        total += item.stack || 0
                    }
                }
            }
        }
        return total
    }

    // 判断道具是否足够
    isEnoughByArray(bag: BagModel, items) {
        for (let i = 0; i < items.length; i++) {
            let itemId = items[i][0]
            let itemNum = items[i][1]
            let num = this.getTotalNumByItemId(bag, itemId)
            if (num < itemNum) {
                return -1
            }
        }
        return 0
    }

    // 判断道具是否足够
    isEnoughByObject(bag: BagModel, items) {
        for (let itemId in items) {
            let num = this.getTotalNumByItemId(bag, Number(itemId))
            if (num < items[itemId]) {
                return -1
            }
        }
        return 0
    }

    // 移除道具
    removeItems(bag: BagModel, items) {
        for (let i = 0; i < items.length; i++) {
            let itemId = items[i][0]
            let itemNum = items[i][1]
            this.removeItemByItemId(bag, itemId, itemNum)
        }
    }

    // 移除道具
    removeItemsByObject(bag: BagModel, items) {
        for (let itemId in items) {
            let itemNum = items[itemId]
            this.removeItemByItemId(bag, itemId, itemNum)
        }
    }

    //交换物品的位置
    transPositionItems(bag: BagModel, pos, topos) {
        let fromItemComponent = bag.items[pos];
        let toItemComponent = bag.items[topos];
        bag.items[pos] = toItemComponent;
        bag.items[topos] = fromItemComponent;
        toItemComponent.pos = topos;
        fromItemComponent.pos = pos;
    }

    //合并物品
    mergeItems(bag: BagModel, frompos, topos, bagType: BagType) {
        if (frompos === topos) {
            return 1; //位置一致，不能合并
        }
        let fromItemComponent = bag.items[frompos];
        let toItemComponent = bag.items[topos];
        if (!fromItemComponent || !toItemComponent) {
            return 1; //有物品不存在不能合并
        }

        if (fromItemComponent.tID !== toItemComponent.tID) {
            return 1; //物品类型不同不能合并
        }

        if (fromItemComponent.lvl !== toItemComponent.lvl) {
            return 1; //物品等级不同不能合并
        }

        let itemConfig = gameConfigHandle.configByID[fromItemComponent.tID]
        let maxStack = itemConfig.Single ? 1 : (itemConfig.MaxStack || MAXSTACK);
        if (bagType == BagType.Bag && itemConfig.Single && fromItemComponent.hp && fromItemComponent.hp == toItemComponent.hp) {
            maxStack = MAXSTACK
        }
        // let maxStack = totalConfigAll.totalConfig.Item[fromItemComponent.tID].Single ? 1 : MAXSTACK;
        let fromstack = fromItemComponent.stack;
        let tostack = toItemComponent.stack;
        if (fromstack >= maxStack) {
            return 0; //起始位置物品堆叠数达到上限，不能进行合并
        }

        if (tostack === maxStack) {
            //置换
            this.transPositionItems(bag, frompos, topos);
            return 0;
        }

        if (tostack + fromstack <= maxStack) {
            fromItemComponent.stack = tostack + fromstack;
            this.removeItemByPosition(bag, topos);
        } else {
            let startstack = maxStack
            let endstack = tostack + fromstack - maxStack;
            fromItemComponent.stack = startstack;
            toItemComponent.stack = endstack;
        }
    }

    //合并包裹中能合并的物品
    mergePackage(bag: BagModel, bagType: BagType) {
        for (let i = 0; i < bag.size - 1; i++) {
            for (let j = i + 1; j < bag.size; j++) {
                this.mergeItems(bag, i, j, bagType);
            }
        }
    }

    //包裹整理  老师写的   使用 sort 函数来进行排序操作
    arrange(player: PlayerModel, bagType: BagType) {
        //整理材料背包  
        if (bagType == BagType.Bag) {
            let bag = player.bag
            this.mergePackage(player.bag, bagType)
            bag.items.sort((item1, item2) => {
                if (item1 && item2) {
                    if (item1.hp !== item2.hp) {
                        return item2.hp - item1.hp
                    } else {
                        return item1.tID - item2.tID
                    }
                } if (!item1 && item2) {
                    return 1;//空的 排到后面去
                } else if (item1 && !item2) {
                    return -1;
                } else {
                    return 1;//都为 空 
                }
            })
            this.initPackag(bag)
        }
        //整理装备背包
        else if (bagType == BagType.Equipment) {
            let bag = player.equipmentBag
            // this.mergePackage(player.bag, bagType)
            //优先按照品质降序排序 再按照等级升序排序 再按照五行降序排列   由于等级的数据在配置文件没改到装备里 所以没有效果
            bag.items.sort((item1, item2) => {
                if (item1 && item2) {
                    if (item1.equipment.quality !== item2.equipment.quality) {
                        return item2.equipment.quality - item1.equipment.quality
                    } else {
                        if (item1.equipment.lvl !== item2.equipment.lvl) {
                            return item2.equipment.lvl - item1.equipment.lvl
                        } else {
                            return item1.tID - item2.tID
                        }
                    }
                } else if (!item1 && item2) {
                    return 1;
                } else if (item1 && !item2) {
                    return -1;
                } else {
                    return 1;
                }
            })
            this.initPackag(bag)
        }
        //整理装备背包
        else if (bagType == BagType.Equipment2) {
            let bag = player.equipmentBag2
            // this.mergePackage(player.bag, bagType)
            //优先按照品质降序排序 再按照等级升序排序 再按照五行降序排列   由于等级的数据在配置文件没改到装备里 所以没有效果
            bag.items.sort((item1, item2) => {
                if (item1 && item2) {
                    if (item1.equipment.quality !== item2.equipment.quality) {
                        return item2.equipment.quality - item1.equipment.quality
                    } else {
                        if (item1.equipment.lvl !== item2.equipment.lvl) {
                            return item2.equipment.lvl - item1.equipment.lvl
                        } else {
                            return item1.tID - item2.tID
                        }
                    }
                } else if (!item1 && item2) {
                    return 1;
                } else if (item1 && !item2) {
                    return -1;
                } else {
                    return 1;
                }
            })
            this.initPackag(bag)
        }
        //整理宝物
        else if (bagType == BagType.Treasure) {
            let bag = player.treasureBag
            //this.mergePackage(player.bag, bagType)
            //优先按照品质降序排序 再按照等级升序排序 
            bag.items.sort((item1, item2) => {
                if (item1 && item2) {
                    if (item1.treasure.quality !== item2.treasure.quality) {
                        return item2.treasure.quality - item1.treasure.quality
                    } else {
                        if (item1.treasure.lvl !== item2.treasure.lvl) {
                            return item2.treasure.lvl - item1.treasure.lvl
                        } else {
                            return item1.tID - item2.tID
                        }
                    }
                } else if (!item1 && item2) {
                    return 1;
                } else if (item1 && !item2) {
                    return -1;
                } else {
                    return 1;
                }
            })
            this.initPackag(bag)
        }
        //整理宝石
        else if (bagType == BagType.Gem) {
            // let bag = player.gemBag
            // bag.items.sort((item1, item2) => {
            //     if (item1 && item2) {
            //         if (item1.lvl !== item2.lvl) {
            //             return item2.lvl - item1.lvl
            //         } else {
            //             return item1.tID - item2.tID
            //         }
            //     } else if (!item1 && item2) {
            //         return 1;
            //     } else if (item1 && !item2) {
            //         return -1;
            //     } else {
            //         return 1;
            //     }
            // })
            // this.initPackag(bag)
        }
    }

}

let bagHandle = new BagHandle()
export default bagHandle

